﻿using Farming.Domain;
using Farming.Domain.DTO;
using Farming.Domain.Traceabilities;
using Farming.Repository;
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Panda.DynamicWebApi;
using Panda.DynamicWebApi.Attributes;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Farming.Application
{
    [DynamicWebApi]
    [ApiExplorerSettings(GroupName = "v1")]
    [Authorize]
    public class AccountService : IDynamicWebApi
    {
        private readonly Repository<Admin> _adminRepository;
        private readonly IConfiguration configuration;
        private readonly IHttpContextAccessor httpContextAccessor;
        
       
       

        public AccountService(Repository<Admin> adminRepository, IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            _adminRepository = adminRepository;
            this.configuration = configuration;
            this.httpContextAccessor = httpContextAccessor;
        
           
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<LoginResult> GetLoginAsync(LoginRequest request)
        {
            LoginResult response = new LoginResult();
            var model = await _adminRepository.GetAllAsync1(d => d.UserName == request.userName);

            if (model.Count() < 1)
            {
                response.Code = -1;
                response.Message = "账户不存在";
            }
            else
            {
                if (model.First().PassWord != request.password)
                {
                    response.Code = -2;
                    response.Message = "密码错误";
                }
                else
                {
                    response.Code = 1;
                    response.Message = "登录成功";
                    response.AdminId = model.First().AdminId;
                    response.Username = model.First().UserName;
                    response.PassWord = model.First().PassWord;



                    model.First().LastLoginIp = httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                    model.First().LastLoginTime = DateTime.Now;
                    await _adminRepository.UpdateDataAsync(model.First());

                    //调用生成Token方法
                    var authInfo = MakeJwtAction(model.First());
                   

                   

                    return new LoginResult<string>
                    {
                        Code = 1,
                        Message = "登陆成功",
                        Data = authInfo
                    };
                }
            }


            return response;
        }
        [HttpPost]
        public async Task<List<Admin>> GetAdmin()
        {
            return await _adminRepository.GetAllAsync();
        }
        public string MakeJwtAction(Admin admin)
        {
            //写Session或Cookies换成JWT


            IList<Claim> claims = new List<Claim> {
                        new Claim(JwtClaimTypes.Id,admin.AdminId.ToString()),
                        new Claim(JwtClaimTypes.Name,admin.UserName),
                    };
            var claimsnew = new List<Claim>
            {
                new Claim("custom_id", admin.AdminId.ToString()),
                new Claim(ClaimTypes.Name, admin.UserName)
            };
          
            var identity = new ClaimsIdentity(claimsnew, "login");
            var claimsPrincipal = new ClaimsPrincipal(identity);
            httpContextAccessor.HttpContext.User = claimsPrincipal; // 确保 User 被正确设置

            //JWT密钥
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:Bearer:SecurityKey"]));

            //算法
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //过期时间
            DateTime expires = DateTime.UtcNow.AddHours(30);


            //Payload负载
            var token = new JwtSecurityToken(
                issuer: configuration["JwtConfig:Bearer:Issuer"],
                audience: configuration["JwtConfig:Bearer:Audience"],
                claims: claims,
                notBefore: DateTime.UtcNow,
                expires: expires,
                signingCredentials: cred
                );

            var handler = new JwtSecurityTokenHandler();

            //生成令牌
            string jwt = handler.WriteToken(token);
            return jwt;
        }
        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<int> DelTest01(int Id)
        {
            var model = await _adminRepository.GetAsync(Id);
            // 存储用户信息到 HttpContext User.Claims 或 Session
           
            return await _adminRepository.Delted(model);
        }
        /// <summary>
        /// 显示列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<Admin>> GetSoftDeleteEntityListAsync()
        {
            return await _adminRepository.GetAllAsync();
        }
        [HttpGet]
        [AllowAnonymous]
        public int  GetErrorMessage()
        {
           
            try
            {
                int a = 0;
                int b = 1;
                int c = b / a;
                return c;
            }
            catch (Exception)
            {

                throw;
            }
        }
        
    }

}
